//
//  GroupListEditViewController.m
//  Guazi
//
//  Created by koolearn on 11-5-16.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "GroupListEditViewController.h"
#import "FriendGroup.h"
#import "TwitterClient.h"
#import "GroupAddViewController.h"
#import "GuaziAppDelegate.h"
#import "GroupService.h"
#import "FriendsViewController.h"


@interface GroupListEditViewController(private)
- (void) buildBarItems;
@end


@implementation GroupListEditViewController

#pragma mark -
#pragma mark Initialization

/*
- (id)initWithStyle:(UITableViewStyle)style {
    // Override initWithStyle: if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
    if ((self = [super initWithStyle:style])) {
    }
    return self;
}
*/


#pragma mark -
#pragma mark View lifecycle


- (void)viewDidLoad {
    [super viewDidLoad];
	
	[self buildBarItems];

	groups = [[NSMutableArray alloc] init];
	deletedGroups = [[NSMutableArray alloc] initWithCapacity:0];
}


- (void)viewWillAppear:(BOOL)animated {
	[groups removeAllObjects];
	[deletedGroups removeAllObjects];
    
    /*
	NSArray* groupList = [TwitterClient getGroups];
     */
    NSArray* groupList = [FriendGroup loadGroups:NO onlyRealGroup:YES];
	for ( FriendGroup* group in groupList ) {
        if ( group.groupId != 0 ) {
            [groups addObject:group];
        }
	}
    
	[self.tableView reloadData];
    [super viewWillAppear:animated];
}



- (void) buildBarItems
{
	self.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd 
																							target:self action:@selector(add)] autorelease];
}


/*
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
}
*/
/*
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
}
*/
/*
- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
}
*/
/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/


#pragma mark - tools methods

- (void) add
{
	GroupAddViewController* controller = [[GroupAddViewController alloc] init];
    controller.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemSave target:controller action:@selector(saveInStackView)] autorelease];
	[self.navigationController pushViewController:controller animated:YES];
	[controller release];
}


//编辑组
- (void) editGroup:(FriendGroup*)group
{
	GroupAddViewController* controller = [[GroupAddViewController alloc] init];
	controller.group = group;
    
    UINavigationController* nav = [[GuaziAppDelegate getAppDelegate] currentNavigationController];
	[nav pushViewController:controller animated:YES];
	[controller release];
}


- (void) delete:(id)sender
{
    UIActionSheet* actionsheet = [[UIActionSheet alloc] initWithTitle:@"您是否确认删除该分组？删除分组后，该分组下的联系人将加入到未分组中。" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:@"确认" otherButtonTitles:nil];
    UIButton* button = (UIButton*) sender;
    actionsheet.tag = button.tag;
    
    [actionsheet showInView:[GuaziAppDelegate getAppDelegate].tabBarController.view];
    [actionsheet release];
}


- (void)deleteGroup:(NSInteger)row
{
	FriendGroup* group = [groups objectAtIndex:row];
    
    BOOL result = [GroupService deleteGroup:group.groupId];
    if ( result ) {
        [deletedGroups addObject:group];
        [groups removeObjectAtIndex:row];
        [self.tableView reloadData];
        
        FriendsViewController* controller = [[GuaziAppDelegate getAppDelegate] friendsViewController];
        [controller refreshDeleteGroup:group];
    }
}


- (void) actionSheet:(UIActionSheet *)actionSheet didDismissWithButtonIndex:(NSInteger)buttonIndex
{
    if ( buttonIndex == 0 ) {
        [self deleteGroup:actionSheet.tag];
    }
}



#pragma mark -
#pragma mark Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
	return 1;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
	return [groups count];
}


// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *CellIdentifier = @"GroupListEditViewCell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    }
    
	FriendGroup* group = [groups objectAtIndex:indexPath.row];
	cell.textLabel.text = group.name;
	cell.textLabel.font = [UIFont systemFontOfSize:18];

	
    UIButton* button = [UIButton buttonWithType:UIButtonTypeCustom];
    [button setBackgroundImage:[UIImage imageNamed:@"row_delete.png"] forState:UIControlStateNormal];
    button.frame = CGRectMake(0, 0, 44, 44);
    button.tag = indexPath.row;
    [button addTarget:self action:@selector(delete:) forControlEvents:UIControlEventTouchUpInside];
    cell.accessoryView = button;

    return cell;
}


- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 50;
}



/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/


/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:YES];
    }   
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/


/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/


/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/


#pragma mark -
#pragma mark Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath 
{
    FriendGroup* group = [groups objectAtIndex:indexPath.row];
    [self editGroup:group];
}


#pragma mark -
#pragma mark Memory management

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Relinquish ownership any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
	[groups release];
	[deletedGroups release];
}


- (void)dealloc {
	[groups release];
	[deletedGroups release];
    [super dealloc];
}


@end

